package com.code.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.code.constant.RedisConstant;
import com.code.dao.SetmealDao;
import com.code.entity.PageResult;
import com.code.pojo.Setmeal;
import com.code.service.SetmealService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 套餐管理业务层实现类
 */

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outputpath;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        // 添加套餐
        setmealDao.add(setmeal);
        setSetMealAndCheckGroup(setmeal.getId(), checkgroupIds);
        // 将图片名称保存到Redis集合
        String fileName = setmeal.getImg();

        if (fileName != null && fileName.length() > 0) {
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, fileName);
        }

        // 新增套餐后需要重新生成静态页面
        generateMobileStaticHtml();
    }


    // 分页
    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> page = setmealDao.selectByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    // 删除
    @Override
    public void deleteById(Integer id) {
        setmealDao.deleteAssociation(id);
        setmealDao.deleteById(id);
    }

    // 查询所有
    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    // 根据ID查询
    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    // 更新数据
    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.deleteAssociation(setmeal.getId());

        setSetMealAndCheckGroup(setmeal.getId(), checkgroupIds);

        setmealDao.update(setmeal);
    }

    // 查询检查组的ID
    @Override
    public List<Integer> findCheckGroupIdBySetmealId(Integer id) {
        return setmealDao.findCheckGroupIdBySetmealId(id);
    }

    // 关联关系
    public void setSetMealAndCheckGroup(Integer setmealId, Integer[] checkgroupIds) {
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                HashMap<String, Integer> map = new HashMap<>();
                map.put("setmeal_id", setmealId);
                map.put("checkgroup_id", checkgroupId);
                setmealDao.setSetMealAndCheckGroup(map);
            }
        }
    }

    // 生成静态页面
    public void generateMobileStaticHtml() {
        // 获取模板所需数据
        List<Setmeal> list = this.findAll();

        // 生成套餐列表静态页面
        generateMobileSetmealListHtml(list);

        //生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(list);
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> list) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("setmealList", list);
        generateHtml("mobile_setmeal.ftl", "m_setmeal.html", map);
    }

    //生成套餐详情静态页面（多个）
    public void generateMobileSetmealDetailHtml(List<Setmeal> list) {
        for (Setmeal setmeal : list) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("setmeal", findById(setmeal.getId()));
            generateHtml("mobile_setmeal_detail.ftl",
                    "setmeal_detail_" + setmeal.getId() + ".html", map);
        }
    }

    // 生成静态页面的方法
    public void generateHtml(String templateName, String htmlPageName, Map<String, Object> dataMap) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;

        try {
            // 加载模板文件
            Template template = configuration.getTemplate(templateName,"utf-8");
            // 生成数据
            File file = new File(outputpath + "\\" + htmlPageName);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"utf-8"));
            // 输出
            template.process(dataMap, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
